package com.example.a2007dou_shop.register

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.a2007dou_shop.entity.SendCodeEntity
import com.example.a2007dou_shop.mvvm.BaseViewModel
import com.google.gson.Gson
import kotlinx.coroutines.launch
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody

class RegisterViewModel:BaseViewModel() {
    //发送验证码
    val sendSuccess = MutableLiveData<SendCodeEntity>()
    val sendFail = MutableLiveData<String>()
    fun sendrcode(phone:String){
        viewModelScope.launch {
            try {
                val result = apiServer.sendrcode(phone)
                sendSuccess.value = result
            }catch (e:Exception){
                sendFail.value = e.message
            }
        }
    }
    //校验验证码
    val checkSuccess = MutableLiveData<SendCodeEntity>()
    val checkFail = MutableLiveData<String>()
    fun checkrcode(phone:String,code:String){
        viewModelScope.launch {
            try {
                val map = mutableMapOf<String,Any>()
                map["phone"] = phone
                map["code"] = code
                val json = Gson().toJson(map)
                val body = RequestBody.create("application/json;charset=utf-8".toMediaType(),json)
                val result = apiServer.checkrcode(body)
                checkSuccess.value = result

            }catch (e:Exception){
                checkFail.value = e.message
            }
        }
    }
    val registerSuccess = MutableLiveData<SendCodeEntity>()
    val registerFail = MutableLiveData<String>()
    fun register(phone:String,username:String,password:String){
        viewModelScope.launch {
            try {
                val map = mutableMapOf<String,Any>()
                map["phone"] = phone
                map["username"] = username
                map["password"] = password
                val json = Gson().toJson(map)
                val body = RequestBody.create("application/json;charset=utf-8".toMediaType(),json)
                val result = apiServer.register(body)
                registerSuccess.value = result

            }catch (e:Exception){
                registerFail.value = e.message
            }
        }
    }

}